package com.edais.actions;

import com.alibaba.fastjson.JSONObject;
import com.edais.dao.RiskEvaluationDao;
import com.edais.dao.UserDao;
import com.edais.domain.*;
import com.edais.log.IpLog;
import com.edais.service.*;
import com.edais.util.*;
import com.edais.vo.UserBankCardVo;
import com.google.gson.JsonObject;
import com.lb.sssq.service.DepositService;
import com.yunzhi.domain.RequestHeader;
import com.yunzhi.domain.ResultCode;
import com.yunzhi.domain.ResultConstant;
import com.yunzhi.domain.ResultDTO;
import com.yunzhi.util.RequestUtil;
import com.yunzhi.util.ResponseUtil;

import javassist.bytecode.stackmap.BasicBlock.Catch;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/user")

public class UserAction implements Serializable {
	private static final Log logger = LogFactory.getLog(UserAction.class);

	@Autowired
	private UserService userService;
	@Autowired
	private CaptchaService captchaService;
	@Autowired
	private UserCardService userCardService;

	@Autowired
	private ChannelWelfareParametersService channelWelfareParametersService;

	@Autowired
	private PointService pointService;

	@Autowired
	private ErrorMessageService errorMessageService;

	@Autowired
	private UserDao usersDao;

	@Autowired
	private RiskEvaluationDao riskEvaluationDao;
	/**
	 * 获取用户手当前绑定手机号
	 * 
	 * @param request
	 * @return response
	 * @throws Exception
	 */
	@RequestMapping(value = "/getUserMobile")
	public void getUserMobile(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		String userId = paramsMap.get("userId");// 用户id

		if (StringUtils.isBlank(userId)) {
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE,
					Consts.ErrorMsg.MSG00001, Message.CnDescriptionExpression.BUSINESSE_ERROR);

			// 处理返回结果
			CommonUtil.responseJson(result, response);
			logger.debug("user/getUserMobile 传入用户id为空");
			return;
		}

		try {
			// 获取当前绑定手机号
			jsonMap = this.userService.getUserMobile(userId);
			// 处理返回结果
			String result = JsonUtil.getJsonStringFromMap(jsonMap);
			CommonUtil.responseJson(result, response);
		} catch (Exception e) {
			logger.error("user/getUserMobile 异常:" + e.getCause());
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE,
					Consts.ErrorMsg.MSG00001, Message.CnDescriptionExpression.BUSINESSE_ERROR);
			CommonUtil.responseJson(result, response);
		}
	}

	/**
	 * 根据邀请码查看邀请人信息
	 */
	@RequestMapping(value = "/getUserInfoByICd")
	public void getUserInfoByICd(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		String invitationCode = paramsMap.get("invitationCd");// 邀请码

		if (StringUtils.isBlank(invitationCode)) {
			jsonMap.put("inviterInfo", "");
			String result = CommonUtil.setResultStringCn(jsonMap, Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE, "");
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			return;
		}

		try {
			// 根据邀请码获取邀请人信息
			User user = userService.getInviterInfo(invitationCode.toUpperCase());
			String inviterInfo = "";

			if (user != null) {
				String mobile = user.getMobile();
				if (StringUtils.isBlank(mobile)) {
					String email = user.getEmail();
					// 邮箱中间*号处理
					inviterInfo = StrUtil.hiddenEmailContent(email);
				} else {
					// 手机中间4位*号处理
					inviterInfo = StrUtil.hiddenMobileContent(mobile);
				}
			}
			jsonMap.put("inviterInfo", inviterInfo);
			String result = CommonUtil.setResultStringCn(jsonMap, Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE, "");
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			return;
		} catch (Exception ex) {
			logger.debug("user/getUserInfoByICd 异常" + ex.getMessage());
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE,
					Consts.ErrorMsg.MSG00001, Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
		}
	}

	/**
	 * 获取验证码
	 * 
	 * @param request
	 * @return response
	 * @throws Exception
	 */
	@RequestMapping(value = "/captcha")
	public void getCaptcha(HttpServletRequest request, HttpServletResponse response) {
		try {
			// 解密请求参数
			JSONObject paramsMap = RequestUtil.decodeDataJson(request);
			// 数据检查
			Map<String, String> checkMap = getCaptchaCheck(paramsMap);
			if (null == checkMap || !Consts.SUCCESS_CODE.equals(checkMap.get("code"))) {
				String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), checkMap.get("code"), "",
						checkMap.get("message"));
				// 处理返回结果
				CommonUtil.responseJson(result, response);
				return;
			}
			// 业务处理
			paramsMap.put("userMobile", checkMap.get("userMobile"));
			// 查询短信发送每日限额次数
			String infoTime = this.userService.getSystemSettingValue("day_captcha_time");
			if (null == infoTime || "".equalsIgnoreCase(infoTime)) {
				infoTime = "5";
			}
			// 查询是否限制短信发送
			ResultDTO result = userService.getCaptcha(paramsMap, infoTime);
			CommonUtil.responseJson(result.toJsonString(), response);
		} catch (Exception e) {
			logger.error("获取验证码发生异常:" + e.getMessage());
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, "",
					Message.CnDescriptionExpression.GET_CAPTCHA_FAILED);
			CommonUtil.responseJson(result, response);
		}
	}

	@RequestMapping(value = "/phoneIsExisted")
	public void phoneIsExisted(HttpServletRequest request, HttpServletResponse response) {
		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		// String phoneNum = paramsMap.get("phoneNum");
		try {
			// 数据检查
			Map<String, String> checkMap = getCheckNum(paramsMap);
			if (0 != checkMap.size() && !Consts.SUCCESS_CODE.equals(checkMap.get("code"))) {
				String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), checkMap.get("code"), "",
						checkMap.get("message"));
				// 处理返回结果
				CommonUtil.responseJson(result, response);
				return;
			}
			/*
			 * Map<String, String> resMap = new HashMap<String,String>();
			 * resMap.put("rescode", Consts.SUCCESS_CODE);
			 * resMap.put("resmsg_cn",
			 * Message.CnDescriptionExpression.USER_CAN_USE);
			 */
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.SUCCESS_CODE, "",
					Message.CnDescriptionExpression.USER_CAN_USE);
			CommonUtil.responseJson(result, response);
		} catch (Exception e) {
			logger.error("检验用户发生异常:" + e.getMessage());
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, "",
					Message.CnDescriptionExpression.USER_IS_EXISTED);
			CommonUtil.responseJson(result, response);
		}
	}

	public Map<String, String> getCheckNum(Map<String, String> paramsMap) throws Exception {
		Map<String, String> resMap = new HashMap<String, String>();
		String mobileNum = paramsMap.get("phoneNum");

		// 手机号合法检查
		boolean flagMobile = mobileNum.matches(Consts.PHONECHECK);
		if (!flagMobile) {
			logger.error("发送格式数据检查失败：手机号非法");
			resMap.put("code", Consts.CHECK_CODE);
			resMap.put("message", Message.CnDescriptionExpression.MOBILE_IS_NON_STANDARD);
			return resMap;
		}
		// 判断手机号是否被使用
		int count = userService.phoneIsExisted(mobileNum);
		// if("REGISTER".equals(type) || "BINDING_MOBILE".equals(type)){
		// 注册及其绑定手机号
		if (count > 0) {
			logger.error("发送格式数据检查失败：注册或者绑定手机号时手机号被使用");
			resMap.put("code", Consts.CHECK_CODE);
			resMap.put("message", Message.CnDescriptionExpression.MOBILE_IS_BOUND);
			return resMap;
		}

		// resMap.put("code", Consts.SUCCESS_CODE);
		// resMap.put("message", Consts.SUCCESS_DESCRIBE);
		// }
		return resMap;
	}

	/**
	 * 发送验证码数据检查
	 * 
	 * @param paramsMap
	 * @return
	 * @throws Exception
	 */
	private Map<String, String> getCaptchaCheck(JSONObject paramsMap) throws Exception {
		Map<String, String> resMap = new HashMap<String, String>();

		// 手机号
		String mobileNum = paramsMap.getString("phoneNum");
		/*
		 * 验证码类别： 注册验证码(REGISTER), 重置登陆密码(FORGET_PASSWORD), 解绑手机(MODIFY_MOBILE),
		 * 绑定手机(BINDING_MOBILE), MODIFY_PASSWORD:修改登陆密码 CASHDRAW:提现,
		 * RESETPASSWORD :修改登录密码/重置登陆密码
		 */
		String type = paramsMap.getString("type");
		// 发送标识（是来自网站用户，还是手机用户）:1：为来自网站的；2：来自手机的
		String setupFlag = paramsMap.getString("setupFlag");
		// 用户id
		String userId = paramsMap.getString("userId");

		String userMobile = "";

		// 验证码类别
		if (StringUtils.isBlank(type)) {
			logger.error("发送验证码数据检查失败：验证码类别为空");
			resMap.put("code", Consts.ERROR_CODE);
			resMap.put("message", Message.CnDescriptionExpression.BUSINESSE_ERROR);
			return resMap;
		}

		// 发送标识
		if (StrUtil.setupFlagCheck(setupFlag) == false) {
			logger.error("发送验证码数据检查失败：发送标识无效！发送标识:" + setupFlag);
			resMap.put("code", Consts.ERROR_CODE);
			resMap.put("message", Message.CnDescriptionExpression.BUSINESSE_ERROR);
			return resMap;
		}

		// 验证码类别
		if ("MODIFY_MOBILE".equals(type) || "MODIFY_PASSWORD".equals(type) || "CASHDRAW".equals(type)) {
			// 用户id
			if (StringUtils.isBlank(userId)) {
				logger.error("发送验证码数据检查失败：用户id为空");
				resMap.put("code", Consts.ERROR_CODE);
				resMap.put("message", Message.CnDescriptionExpression.BUSINESSE_ERROR);
				return resMap;
			}
			// 查询用户的手机号
			userMobile = captchaService.getMobileById(userId);
		} else if ("REGISTER".equals(type) || "FORGET_PASSWORD".equals(type) || "BINDING_MOBILE".equals(type)
				|| "RESETPASSWORD".equals(type)) {
			// 手机号
			if (StringUtils.isBlank(mobileNum)) {
				logger.error("发送验证码数据检查失败：手机号为空");
				resMap.put("code", Consts.CHECK_CODE);
				resMap.put("message", Message.CnDescriptionExpression.MOBILE_IS_NULL);
				return resMap;
			}
			// 手机号合法检查
			boolean flagMobile = mobileNum.matches(Consts.PHONECHECK);
			if (!flagMobile) {
				logger.error("发送验证码数据检查失败：手机号非法");
				resMap.put("code", Consts.CHECK_CODE);
				resMap.put("message", Message.CnDescriptionExpression.MOBILE_IS_NON_STANDARD);
				return resMap;
			}
			// 判断手机号是否被使用
			int count = userService.phoneIsExisted(mobileNum);
			if ("REGISTER".equals(type) || "BINDING_MOBILE".equals(type)) {
				// 注册及其绑定手机号
				if (count > 0) {
					logger.error("发送验证码数据检查失败：注册或者绑定手机号时手机号被使用");
					resMap.put("code", Consts.CHECK_CODE);
					resMap.put("message", Message.CnDescriptionExpression.MOBILE_IS_BOUND);
					return resMap;
				}
			} else {
				// 重置密码
				if (count <= 0) {
					logger.error("发送验证码数据检查失败：重置密码时手机号无注册");
					resMap.put("code", Consts.CHECK_CODE);
					resMap.put("message", Message.CnDescriptionExpression.MOBILE_NOT_EXIST);
					return resMap;
				}
			}
			userMobile = mobileNum;
		} else {
			logger.error("发送验证码数据检查失败：验证码类别无效！验证码类别：" + type);
			resMap.put("code", Consts.ERROR_CODE);
			resMap.put("message", Message.CnDescriptionExpression.BUSINESSE_ERROR);
			return resMap;
		}

		resMap.put("userMobile", userMobile);
		resMap.put("code", Consts.SUCCESS_CODE);
		resMap.put("message", Consts.SUCCESS_DESCRIBE);
		return resMap;
	}

	/**
	 * 验证码检验
	 * 
	 * @param request
	 * @return response
	 * @throws Exception
	 */
	@RequestMapping(value = "/checkCaptcha")
	public void checkCaptcha(HttpServletRequest request, HttpServletResponse response) {

		if (!RequestUtil.validSign(request)) {
			logger.info("无效签名");
			ResponseUtil.write(response, ResultConstant.INVALID_SIGN);
			return;
		}



		try {

			JSONObject params = RequestUtil.decodeDataJson(request);
			logger.info("data：" + params);
			// 数据检查
			ResultDTO checkResult = checkCaptchaCheck(params);
			if (null == checkResult || checkResult.codeEq(ResultCode.FAILED)) {
				ResponseUtil.write(response,checkResult);
				return;
			}

			logger.debug("请求手机号：" + params.getString("phoneNum") + "请求验证码：" + params.getString("checkCode") + "发送标识:"
					+ params.getString("setupFlag"));

			// 业务处理
			ResultDTO result = userService.checkCaptcha(params);
			ResponseUtil.write(response,result);
		} catch (Exception e) {
			logger.error("获取验证码发生异常:" + e.getMessage());
			ResponseUtil.write(response,new ResultDTO(ResultCode.FAILED,
					Message.CnDescriptionExpression.GET_CAPTCHA_FAILED));
		}
	}

	/**
	 * 校验验证码数据检查
	 * 
	 * @param params
	 * @return
	 * @throws Exception
	 */
	private ResultDTO checkCaptchaCheck(JSONObject params) throws Exception {

		String phoneNum = params.getString("phoneNum");
		String checkCode = params.getString("checkCode");
		// 发送标识（是来自网站用户，还是手机用户）:1：为来自网站的；2：来自手机的
		String setupFlag = params.getString("setupFlag");

		// 手机号码
		if (StringUtils.isBlank(phoneNum)) {
			logger.error("校验验证码数据检查失败：手机号码为空");
			return new ResultDTO(ResultCode.FAILED,
					Message.CnDescriptionExpression.MOBILE_IS_NULL);
		}

		// 验证码
		if (StringUtils.isBlank(checkCode)) {
			logger.error("校验验证码数据检查失败：验证码为空");
			return new ResultDTO(ResultCode.FAILED,
					Message.CnDescriptionExpression.CAPTCHA_IS_NULL);
		}

		// 发送标识
		if (!StrUtil.setupFlagCheck(setupFlag)) {
			logger.error("校验验证码数据检查失败：发送标识无效！发送标识:" + setupFlag);
			return ResultConstant.FAILED;
		}
		return ResultConstant.SUCCESS;
	}

	/**
	 * 注册（目前只针对手机注册 ）
	 * 
	 * @param request
	 * @return response
	 * @throws Exception
	 */
	@RequestMapping(value = "/register")
	public void register(HttpServletRequest request, HttpServletResponse response) {

		if (!RequestUtil.validSign(request)) {
			logger.info("无效签名");
			ResponseUtil.write(response, ResultConstant.INVALID_SIGN);
			return;
		}

		try {
			JSONObject params = RequestUtil.decodeDataJson(request);
			logger.info("data：" + params);

			String userName = params.getString("userName");// 用户名-手机号
			String password = params.getString("password");// 密码
			String channel = params.getString("channel");// 渠道
			// 发送标识（是来自网站用户，还是手机用户）:1：为来自网站的；2：来自手机的
			String setupFlag = params.getString("setupFlag");
			String invitationCode = params.getString("invitationCd");// 邀请码


			String ip = CommonUtil.getClientIP(request);

			IpLogBean logBean = new IpLogBean();
			logBean.setIp(ip);
			logBean.setAction("注册");
			logBean.setStatus(Consts.ERROR_CN);
			if ("2".equals(setupFlag)) {
				logBean.setDetail(userName + "在APP端进行了注册操作");
			} else {
				logBean.setDetail(userName + "在WEB端进行了注册操作");
			}


			ResultDTO checkResult = registerCheck(params);
			if (null == checkResult || checkResult.codeEq(ResultCode.FAILED)) {
				ResponseUtil.write(response,checkResult);
				return;
			}

			if (StringUtils.isBlank(channel)) {
				params.put("channel", "OTHERS");
				channel = "OTHERS";
			}

			// 创建用户
			User user = new User();
			String passwordMd5 = MD5.md5(password);
			user.setMobile(userName);
			user.setPassword(passwordMd5);
			user.setChannel(channel);
			user.setLastest_login_ip(ip);
			String token = "register" + "_" + CommonUtil.getUuid();
			user.setLogin_token(token);
			if ("2".equals(setupFlag)) {
				user.setUtm_source_type("MOBILE");// 用户来源类型（CHANNEL:渠道-线上;AGENCY:机构-线下;AT_SYSTEM:爱特系统用户;AGENCY_SYSTEM:机构系统用户;）
			} else {
				user.setUtm_source_type("CHANNEL");// 用户来源类型（CHANNEL:渠道-线上;AGENCY:机构-线下;AT_SYSTEM:爱特系统用户;AGENCY_SYSTEM:机构系统用户;）
			}

			// 注册邀请码
			if (StringUtils.isNotBlank(invitationCode)) {
				user.setInviterInvitationCode(invitationCode.toUpperCase());
			}

			// 添加用户(T_TUSER表和USER_INFO表)
			this.userService.addUsers(user);

			// 注册成功
			Map<String, Object> jsonMap = new HashMap<>();
			jsonMap.put("userId", user.getId());
			jsonMap.put("userName", userName);
			jsonMap.put("identityName", "");
			jsonMap.put("idCard", "");
			jsonMap.put("ftpPathOriginal", "");
			jsonMap.put("ftpPathDispose", "");
			jsonMap.put("emailValidate", user.getEmail_validate());
			jsonMap.put("idcardValidate", "N");
			jsonMap.put("mobileValidate", user.getMobile_validate());
			jsonMap.put("email", "");
			jsonMap.put("mobile", user.getMobile());
			jsonMap.put("bankCardValidate", "N");

			// uuid生成-2.1.0版本新增
			jsonMap.put("uuid", user.getLogin_token());

			logBean.setStatus(Consts.SUCCESS_CN);
			if (StringUtils.isNotBlank(ip)) {
				logBean.setUser(user.getId() + "");
				IpLog.printIpLog(logBean);
			}

			// 按渠道统一发放福利
			try {
				Map<String, Object> welfareParams = new HashMap<String, Object>();
				welfareParams.put("userId", user.getId());
				welfareParams.put("channelId", user.getUtm_source());
				welfareParams.put("mobile", user.getMobile());
				welfareParams.put("channelEnName", channel);
				channelWelfareParametersService.addWelfareBychannelEnName(welfareParams, request);
			} catch (Exception e) {
				logger.error("注册赠送福利异常:" + e.getMessage());
			}

			// 注册送积分
			if (null != user.getId() && !StringUtil.isEmpty(user.getMobile())) {
				logger.info("#### 开始执行--->注册送积分 #####");
				pointService.registerPoint(user);
				logger.info("#### 执行完成--->注册送积分 #####");
			} else {
				logger.info("#### 注册送积分时，用户信息有误，userId=" + user.getId() + ",mobile=" + user.getMobile() + " ####");
			}

			ResultDTO result = new ResultDTO(ResultCode.SUCCESS);
			result.setRecord(jsonMap);
			ResponseUtil.write(response,result);
		} catch (Exception e) {
			logger.error("注册异常:" + e.getMessage());
			ResponseUtil.write(response,ResultConstant.FAILED);
		}
	}

	/**
	 * 注册数据检查
	 * 
	 * @param params
	 * @return
	 * @throws Exception
	 */
	private ResultDTO registerCheck(JSONObject params) throws Exception {

		String userName = params.getString("userName");// 用户名-手机号
		String password = params.getString("password");// 密码
//		String channel = params.getString("channel");// 渠道
		String setupFlag = params.getString("setupFlag");
		String invitationCode = params.getString("invitationCd");// 邀请码
		String checkCode = params.getString("checkCode");// 验证码

		// 校验用户名不能为空
		if (StringUtils.isBlank(userName)) {
			logger.error("注册数据检查失败： 用户名为空");
			return new ResultDTO(ResultCode.FAILED,
					Message.CnDescriptionExpression.USER_IS_NULL);
		}

		// 校验密码不能为空
		if (StringUtils.isBlank(password)) {
			logger.error("注册数据检查失败： 密码为空");
			return new ResultDTO(ResultCode.FAILED,
					Message.CnDescriptionExpression.PASSWORD_IS_NULL);
		}

		// 验证码
		if (StringUtils.isBlank(checkCode)) {
			logger.error("注册数据检查失败：验证码为空");
			return new ResultDTO(ResultCode.FAILED,
					Message.CnDescriptionExpression.CAPTCHA_IS_NULL);
		}

		// 发送标识
		if (!StrUtil.setupFlagCheck(setupFlag)) {
			logger.error("注册数据检查失败： 发送标识无效！发送标识:" + setupFlag);
			return ResultConstant.FAILED;
		}

		// 非法手机号检查
		boolean flag = userName.matches(Consts.PHONECHECK);
		if (!flag) {
			logger.error("注册数据检查失败：  手机号格式不对");
			return new ResultDTO(ResultCode.FAILED,
					Message.CnDescriptionExpression.MOBILE_IS_NON_STANDARD);
		}

		// 密码为6-20位数字或大小写字母
		boolean flagPassword = password.matches("[a-zA-Z0-9]{6,20}");
		if (!flagPassword) {
			logger.error("注册数据检查失败：  密码不规范");
			return new ResultDTO(ResultCode.FAILED,
					Message.CnDescriptionExpression.PASSWORD_IS_NON_STANDARD);
		}

		// 先判断用户是否存在(目前只针对手机用户)
		int count = userService.phoneIsExisted(userName);
		if (count > 0) {
			logger.error("注册数据检查失败：  手机号已注册");
			return new ResultDTO(ResultCode.FAILED,
					Message.CnDescriptionExpression.USER_IS_EXISTED);
		}

		// 邀请码检查,如果填写了邀请码，就必须是非本人且存在的邀请码
		if (StringUtils.isNotBlank(invitationCode)) {
			// 判读输入的邀请码是否合法（非本人且存在的）
			int codeCount = userService.getInviteCodeCount(invitationCode.toUpperCase());
			if (codeCount == 0) {
				logger.error("注册数据检查失败：  输入邀请码不存在！");
				return new ResultDTO(ResultCode.FAILED,
						Message.CnDescriptionExpression.INVITATIONCD_IS_WRONG);
			}
		}

		// 验证码检查
		ResultDTO checkResult = userService.checkCaptcha(params);
		// 验证码验证码检查失败
		if (null == checkResult || checkResult.codeEq(ResultCode.FAILED)) {
			logger.error("注册数据检查失败： 验证码检验失败！");
			return new ResultDTO(ResultCode.FAILED,
					Message.CnDescriptionExpression.CHECK_CAPTCHA_FAILED);
		}
		return ResultConstant.SUCCESS;
	}

	/**
	 * 登陆
	 * 
	 * @param request
	 * @return response
	 * @throws Exception
	 */
	@RequestMapping(value = "/login")
	public void login(HttpServletRequest request, HttpServletResponse response) {

		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);

		String userName = paramsMap.get("userName");// 用户名
		String setupFlag = paramsMap.get("setupFlag");// 发送标识（是来自网站用户，还是手机用户）:1：为来自网站的；2：来自手机的

		String ip = CommonUtil.getClientIP(request);

		IpLogBean logBean = new IpLogBean();
		logBean.setIp(ip);
		logBean.setAction("登录");
		logBean.setStatus(Consts.ERROR_CN);
		if ("2".equals(setupFlag)) {
			logBean.setDetail(userName + "在APP端进行了登录操作");
		} else {
			logBean.setDetail(userName + "在WEB端进行了登录操作");
		}

		try {
			Map<String, String> checkMap = loginCheck(paramsMap);
			if (null == checkMap || !Consts.SUCCESS_CODE.equals(checkMap.get("code"))) {
				String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), checkMap.get("code"), "",
						checkMap.get("message"));
				// 处理返回结果
				CommonUtil.responseJson(result, response);
				return;
			}

			// 登陆主处理
//			String result = userService.dealLogin(paramsMap);

			if (StringUtils.isNotBlank(paramsMap.get("userId"))) {
				logBean.setStatus(Consts.SUCCESS_CN);
				logBean.setUser(paramsMap.get("userId"));
				IpLog.printIpLog(logBean);
			}

//			CommonUtil.responseJson(result, response);
		} catch (Exception e) {
			logger.error("登陆异常:" + e.getMessage());
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, "",
					Message.CnDescriptionExpression.BUSINESSE_ERROR);
			CommonUtil.responseJson(result, response);
		}
	}

	/**
	 * 登陆数据检查
	 * 
	 * @param paramsMap
	 * @return
	 * @throws Exception
	 */
	private Map<String, String> loginCheck(Map<String, String> paramsMap) throws Exception {
		Map<String, String> resMap = new HashMap<String, String>();
		String userName = paramsMap.get("userName");// 用户名
		String password = paramsMap.get("password");// 密码
		String type = paramsMap.get("type");// 登陆类型：手机或者邮箱
		String setupFlag = paramsMap.get("setupFlag");// 发送标识（是来自网站用户，还是手机用户）:1：为来自网站的；2：来自手机的

		if (StringUtils.isBlank(userName)) {
			logger.error("登陆数据检查失败： 用户名为空");
			resMap.put("code", Consts.CHECK_CODE);
			resMap.put("message", Message.CnDescriptionExpression.USER_IS_NULL);
			return resMap;
		}

		if (StringUtils.isBlank(password)) {
			logger.error("登陆数据检查失败： 密码为空");
			resMap.put("code", Consts.CHECK_CODE);
			resMap.put("message", Message.CnDescriptionExpression.PASSWORD_IS_NULL);
			return resMap;
		}

		if (StringUtils.isBlank(type)) {
			logger.error("登陆数据检查失败： 登陆类型为空");
			resMap.put("code", Consts.ERROR_CODE);
			resMap.put("message", Message.CnDescriptionExpression.BUSINESSE_ERROR);
			return resMap;
		}

		if (!("mobile".equals(type) || "mail".equals(type))) {
			logger.error("登陆数据检查失败： 登陆类型为空");
			resMap.put("code", Consts.ERROR_CODE);
			resMap.put("message", Message.CnDescriptionExpression.BUSINESSE_ERROR);
			return resMap;
		}

		// 发送标识
		if (StrUtil.setupFlagCheck(setupFlag) == false) {
			logger.error("登陆数据检查失败： 发送标识无效！发送标识:" + setupFlag);
			resMap.put("code", Consts.ERROR_CODE);
			resMap.put("message", Message.CnDescriptionExpression.BUSINESSE_ERROR);
			return resMap;
		}

		resMap.put("code", Consts.SUCCESS_CODE);
		resMap.put("message", Consts.SUCCESS_DESCRIBE);
		return resMap;
	}

	/**
	 * 更新用户头像信息
	 */
	@RequestMapping(value = "/modifySculpture", method = RequestMethod.POST)
	public void modifySculpture(HttpServletRequest request, HttpServletResponse response) {

		Map<String, Object> jsonMap = new HashMap<String, Object>();
		String logInfo = "更新用户头像—modifySculpture ";
		logger.info(logInfo+"开始");
		//签名校验
		if (!RequestUtil.validSign(request)) {
			logger.info(logInfo+"无效签名");
			ResponseUtil.write(response, ResultConstant.INVALID_SIGN);
			return;
		}

		//token校验
		if (!RequestUtil.validToken(request)) {
			logger.info(logInfo+"无效token");
			ResponseUtil.write(response, ResultConstant.INVALID_TOKEN);
			return;
		}

		//未登录校验
		RequestHeader header = RequestUtil.decodeHeader(request);
		if (header.getUserId() == null) {
			logger.info(logInfo+"未登录");
			ResponseUtil.write(response, ResultConstant.NOT_LOGIN);
			return;
		}

		try {

			String userId = header.getUserId().toString();// 用户id
			logInfo=logInfo+userId ;
			// 校验用户
			User temp = this.userService.getUserDetail(userId);
			if (temp == null) {
				logger.info(logInfo+"用户不存在！");
				ResultDTO resultDTO=new ResultDTO(ResultCode.FAILED,"用户不存在！");
				ResponseUtil.write(response,resultDTO);
				return;
			}

			/** 上传操作 */
			logger.info(logInfo+"开始接收文件");
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			MultipartFile imagePartFile=multipartRequest.getFile("img");
			if (null == imagePartFile) {
				logger.info(logInfo+"请上传文件");
				ResultDTO resultDTO=new ResultDTO(ResultCode.FAILED,"请上传文件！");
				ResponseUtil.write(response,resultDTO);
				return;
			}

			String fileContentType =null;// 上传图片类型:jpg、png*/
			if(imagePartFile.getOriginalFilename().contains(".")){
				fileContentType=imagePartFile.getOriginalFilename().substring(imagePartFile.getOriginalFilename().indexOf(".")+1);
			}

			// 检查用户和文件类型
			if (StringUtils.isBlank(fileContentType)) {
				logger.info(logInfo+"用户名/文件类型为空");
				ResultDTO resultDTO=new ResultDTO(ResultCode.FAILED,"头像设置数据检查失败：文件类型为空");
				ResponseUtil.write(response,resultDTO);
				return;
			}
			logger.info(logInfo+"上传头像类型：" + fileContentType);
			// 校验文件类型
			if (!("jpg".equalsIgnoreCase(fileContentType) || "png".equalsIgnoreCase(fileContentType))) {
				logger.info(logInfo+" 文件类型不正确");
				ResultDTO resultDTO=new ResultDTO(ResultCode.FAILED,"头像设置数据检查失败：文件类型不正确");
				ResponseUtil.write(response,resultDTO);
				return;
			}

			// 进行上传，获取结果
			Map<String, Object> mapResult = this.userService.modifySculpture(imagePartFile,userId,logInfo);

			// 上传原图
			String ftpPathOriginal =(String) mapResult.get("ftpPathOriginal");
			// 上传缩略图
			String ftpPathDispose =(String) mapResult.get("ftpPathDispose");

			if(StringUtils.isBlank(ftpPathOriginal)||StringUtils.isBlank(ftpPathDispose)){
				logger.error(logInfo+"上传头像失败" );
				ResultDTO resultDTO=new ResultDTO(ResultCode.FAILED,Message.CnDescriptionExpression.UPLOAD_SCULPTURE_FAIL);
				ResponseUtil.write(response,resultDTO);
				return;
			}
			// 上传原图
			jsonMap.put("ftpPathOriginal", ftpPathOriginal);
			// 上传缩略图
			jsonMap.put("ftpPathDispose", ftpPathDispose);

			logger.info(logInfo+"结束");
			ResultDTO resultDTO=new ResultDTO(ResultCode.SUCCESS,Consts.SUCCESS_DESCRIBE);
			resultDTO.setRecord(jsonMap);
			ResponseUtil.write(response,resultDTO);
		} catch (Exception e) {
			logger.error(logInfo+"异常:",e);
			ResultDTO resultDTO=new ResultDTO(ResultCode.FAILED,Message.CnDescriptionExpression.UPLOAD_SCULPTURE_FAIL);
			ResponseUtil.write(response,resultDTO);
		}
	}

	/**
	 * 登陆密码重置(目前只限手机账户重置密码)
	 * 
	 * @param request
	 * @return response
	 * @throws Exception
	 */
	@RequestMapping(value = "/resetPassword")
	public void resetPassword(HttpServletRequest request, HttpServletResponse response) {
		String logInfo="";
		try {
			if (!RequestUtil.validSign(request)) {
				logger.info("无效签名");
				ResponseUtil.write(response, ResultConstant.INVALID_SIGN);
				return;
			}
		
			
			
			// 解密请求参数
			JSONObject params = RequestUtil.decodeDataJson(request);
		
			String password = params.getString("password");
			// 验证码
			String checkCode = params.getString("checkCode");
			// 发送标识
			String setupFlag = params.getString("setupFlag");
			//用户 手机号
			String mobile =params.getString("mobile");

			 logInfo="用户mobile="+mobile+"登陆密码重置";
			if (StringUtils.isBlank(mobile)) {
				logger.info(logInfo+"手机号为空");
				ResultDTO<String> checkDto = new ResultDTO<>(ResultCode.FAILED,
						Message.CnDescriptionExpression.BUSINESSE_ERROR);
				ResponseUtil.write(response, checkDto);
				return;
			}

			if (StringUtils.isBlank(checkCode)) {
				logger.info(logInfo+"登陆密码重置：验证码为空");
				ResultDTO<String> checkDto = new ResultDTO<>(ResultCode.FAILED,
						Message.CnDescriptionExpression.CAPTCHA_IS_NULL);
				ResponseUtil.write(response, checkDto);
				return;
			}
			
			// 非法手机号检查
			boolean flag = mobile.matches(Consts.PHONECHECK);
			if (!flag) {
				logger.info(logInfo+"登陆密码重置：手机号格式不对");
				ResultDTO<String> checkDto = new ResultDTO<>(ResultCode.FAILED,
						Message.CnDescriptionExpression.MOBILE_IS_NON_STANDARD);
				ResponseUtil.write(response, checkDto);
				return;
			}

			// 判断验证码是否正确
		
			params.put("phoneNum", mobile);
			ResultDTO checkResult = this.userService.checkCaptcha(params);
			// 判断验证码是否正确
			if (null == checkResult || checkResult.codeEq(ResultCode.FAILED)) {
				logger.info(logInfo+"登陆密码重置：验证码输入错误！");
				ResponseUtil.write(response, checkResult);
				return;
			}
	

			// 新密码为6-20位数字或大小写字母
			flag = password.matches("^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,17}$");
			if (!flag) {
				logger.info(logInfo+"登陆密码重置：密码不规范，请输入6-16位数字和英文组合的密码");
				ResultDTO<String> checkDto = new ResultDTO<>(ResultCode.FAILED,
						Message.CnDescriptionExpression.PASSWORD_IS_NON_STANDARD);
				ResponseUtil.write(response, checkDto);
				return;
			}

			String passwordMd5 = MD5.md5(password);
			// 先判断用户是否存在(目前只针对手机用户)
			int count = userService.phoneIsExisted(mobile);
			if (count <= 0) {
				logger.info(logInfo+"登陆密码重置：手机号未注册");
				ResultDTO<String> checkDto = new ResultDTO<>(ResultCode.FAILED,
						Message.CnDescriptionExpression.MOBILE_NOT_EXIST);
				ResponseUtil.write(response, checkDto);
				return;
			}

			String type = "mobile";
			this.userService.resetPsw(mobile, passwordMd5, type);

			ResultDTO<String> checkDto = new ResultDTO<>(ResultCode.SUCCESS,
					Consts.SUCCESS_DESCRIBE);
			ResponseUtil.write(response, checkDto);
			return;
		} catch (Exception e) {
			logger.error(logInfo+"登陆密码重置：异常:", e);
			
			ResultDTO<String> checkDto = new ResultDTO<>(ResultCode.FAILED,
					Message.CnDescriptionExpression.BUSINESSE_ERROR);
			ResponseUtil.write(response, checkDto);
			return;
		}
	}
	@RequestMapping(value = "/checkSmsCode")
	public void checkSmsCode(HttpServletRequest request, HttpServletResponse response){
		String logInfo="";
		try {
				if (!RequestUtil.validSign(request)) {
					logger.info("交易密码重置短信验证码校验接口无效签名");
					ResponseUtil.write(response, ResultConstant.INVALID_SIGN);
					return;
				}
			
				RequestHeader header = RequestUtil.decodeHeader(request);
				logger.info("header：" + header.toString());			
				
				// 解密请求参数
				JSONObject params = RequestUtil.decodeDataJson(request);
			
				// 验证码
				String checkCode = params.getString("checkCode");
				// 发送标识
				String setupFlag = params.getString("setupFlag");
				//用户 手机号
				String mobile =params.getString("mobile");
				
				logInfo="用户mobile"+mobile;
				if (StringUtils.isBlank(mobile)) {
					logger.info(logInfo+"交易密码重置短信验证码校验：手机号为空");
					ResultDTO<String> checkDto = new ResultDTO<>(ResultCode.FAILED,
							Message.CnDescriptionExpression.BUSINESSE_ERROR);
					ResponseUtil.write(response, checkDto);
					return;
				}
		
				if (StringUtils.isBlank(checkCode)) {
					logger.info(logInfo+"登陆密码重置短信验证码校验：验证码为空");
					ResultDTO<String> checkDto = new ResultDTO<>(ResultCode.FAILED,
							Message.CnDescriptionExpression.CAPTCHA_IS_NULL);
					ResponseUtil.write(response, checkDto);
					return;
				}
				
				// 非法手机号检查
				boolean flag = mobile.matches(Consts.PHONECHECK);
				if (!flag) {
					logger.info(logInfo+"登陆密码重置短信验证码校验：手机号格式不对");
					ResultDTO<String> checkDto = new ResultDTO<>(ResultCode.FAILED,
							Message.CnDescriptionExpression.MOBILE_IS_NON_STANDARD);
					ResponseUtil.write(response, checkDto);
					return;
				}
		
				// 判断验证码是否正确
			
				params.put("phoneNum", mobile);
				ResultDTO checkResult = this.userService.checkCaptcha(params);
				logger.info(logInfo+"登陆密码重置短信验证码校验：成功");
				// 判断验证码是否正确
				ResponseUtil.write(response, checkResult);
				return;
				
		} catch (Exception e) {
			logger.error(logInfo+"登陆密码重置短信验证码校验：异常:", e);
			
			ResultDTO<String> checkDto = new ResultDTO<>(ResultCode.FAILED,
					Message.CnDescriptionExpression.BUSINESSE_ERROR);
			ResponseUtil.write(response, checkDto);
			return;
		}
	}
	

	/**
	 * 修改登录密码
	 */
	@RequestMapping(value = "/updatePassword")
	public void updatePassword(HttpServletRequest request, HttpServletResponse response) {
		
		String logInfo="";
		try {

			if (!RequestUtil.validSign(request)) {
				logger.info("无效签名");
				ResponseUtil.write(response, ResultConstant.INVALID_SIGN);
				return;
			}
			if (!RequestUtil.validToken(request)) {
				logger.info("无效token");
				ResponseUtil.write(response, ResultConstant.INVALID_TOKEN);
				return;
			}
			RequestHeader header = RequestUtil.decodeHeader(request);
			logger.info("header：" + header.toString());
			
			Long userId = header.getUserId();
			if (userId == null) {
				ResponseUtil.write(response, ResultConstant.NOT_LOGIN);
				return;
			}
			 User user = this.userService.getUserDetail(userId.toString());
			    if(user==null){
			    	ResultDTO<String> result = new ResultDTO<>(ResultCode.FAILED,
							Message.CnDescriptionExpression.BUSINESSE_ERROR);
					ResponseUtil.write(response, result);
					return;
			    }
			logInfo="用户mobile="+user.getMobile()+"调用修改登录密码";

			// 解密请求参数
			JSONObject paramsMap = RequestUtil.decodeDataJson(request);
			logger.info(logInfo+"data：" + paramsMap.toString());
			String password = paramsMap.getString("password");
			String passwordOld = paramsMap.getString("passwordOld");


			if (StringUtils.isBlank(password)) {
				logger.info(logInfo+"登陆密码重置：新密码为空");
				ResultDTO<String> checkDto = new ResultDTO<>(ResultCode.FAILED,
						Message.CnDescriptionExpression.PASSWORD_IS_NULL);
				ResponseUtil.write(response, checkDto);
				return;
			}

		 
			String passwordMd5 = MD5.md5(password);
			String passwordOldMd5 = MD5.md5(passwordOld);

			if (!passwordOldMd5.equals(user.getPassword())) {
				logger.info(logInfo+"登陆密码重置：原有登录密码输入有误");
				ResultDTO<String> checkDto = new ResultDTO<>(ResultCode.FAILED,
						Message.CnDescriptionExpression.LOGIN_PASSWORD_ERROR);
				ResponseUtil.write(response, checkDto);
				return;
			}

			// 非法手机号检查
			boolean flag = user.getMobile().matches(Consts.PHONECHECK);
			if (!flag) {
				logger.info(logInfo+"登陆密码重置：手机号格式不对");
				ResponseUtil.write(response, new ResultDTO(ResultCode.FAILED,
						Message.CnDescriptionExpression.MOBILE_IS_NON_STANDARD));
				return;
				
			}

			// 新密码为6-20位数字或大小写字母
			flag = password.matches("^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,17}$");
			if (!flag) {
				logger.info(logInfo+"登陆密码重置：密码不规范，请输入6-16位数字和英文组合的密码");
				ResponseUtil.write(response, new ResultDTO(ResultCode.FAILED,
						Message.CnDescriptionExpression.PASSWORD_IS_NON_STANDARD));
				return;
			}

			// 先判断用户是否存在(目前只针对手机用户)
			int count = userService.phoneIsExisted(user.getMobile());
			if (count <= 0) {
				logger.info(logInfo+"登陆密码重置：手机号未注册");
				ResponseUtil.write(response, new ResultDTO<>(ResultCode.FAILED,
						Message.CnDescriptionExpression.MOBILE_NOT_EXIST));
				return;
			}

			String type = "mobile";
			this.userService.resetPsw(user.getMobile(), passwordMd5, type);
			ResponseUtil.write(response, new ResultDTO<>(ResultCode.SUCCESS,
					Consts.SUCCESS_DESCRIBE));
			return;
			
		} catch (Exception e) {
			logger.error(logInfo+"登陆密码修改：异常:" , e);
			ResponseUtil.write(response, new ResultDTO<>(ResultCode.FAILED,
					Message.CnDescriptionExpression.BUSINESSE_ERROR));
			return;
		}
	}

	/**
	 * 获取用户实名认证信息
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/getIdcardInfo")
	public void getIdcardInfo(HttpServletRequest request, HttpServletResponse response) throws Exception{
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		if (!RequestUtil.validSign(request)) {
			logger.info("无效签名");
			ResponseUtil.write(response, ResultConstant.INVALID_SIGN);
			return;
		}
		if (!RequestUtil.validToken(request)) {
			logger.info("无效token");
			ResponseUtil.write(response, ResultConstant.INVALID_TOKEN);
			return;
		}
		RequestHeader header = RequestUtil.decodeHeader(request);
		logger.info("header：" + header.toString());
		String userId = String.valueOf(header.getUserId());

		if (StringUtils.isBlank(userId)) {
			logger.error("获取用户实名认证信息数据检查失败：用户id为空");
			ResponseUtil.write(response, new ResultDTO(ResultCode.FAILED,Message.CnDescriptionExpression.BUSINESSE_ERROR));
			return;
		}

		//通过userId查询用户是否进行风险评估
		RiskEvaluation risk =new RiskEvaluation();
		if("null".equalsIgnoreCase(userId)){
			risk.setIsRisk("N");
			risk.setRiskType("未评估");
		}else{
			risk = riskEvaluationDao.selectRiskEvaluationByUserId(Integer.parseInt(userId));
			if(risk == null){
				risk =new RiskEvaluation();
				risk.setIsRisk("N");
				risk.setRiskType("未评估");
			}
		}

		jsonMap.put("isRiskEvaluation",risk.getIsRisk());

		// 判断是否已实名认证
		User user = this.userService.getUserDetail(userId);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");

		// 查询是否绑定银行卡
			if ("Y".equals(user.getIdcard_validate())) {

			HashMap<String,Object> userPayCdParam = new HashMap<String,Object>();
			userPayCdParam.put("userId", userId);
			Map<String, Object> userCardMap = this.userCardService.queryUserCardInfoByUserId(userPayCdParam);

			try{
                if (Integer.parseInt(userCardMap.get("userCardInfoCount").toString()) != 0) {
                    jsonMap.put("bankCardValidate", "Y");
                    jsonMap.put("isBinding","Y");
                }else {
                    jsonMap.put("bankCardValidate", "N");
                    jsonMap.put("isBinding","N");
                }
            }catch (Exception e){
                jsonMap.put("bankCardValidate", "N");
                jsonMap.put("isBinding","N");
            }

			if("1".equals(user.getIs_create_acct())){
				// 已实名认证过就获取真实信息
				UserInfo userInfo = this.userService.getUserInfo(userId);
				if (null == userInfo) {
					jsonMap.put("idcardValidate", "N");
					jsonMap.put("idCard", "");
					jsonMap.put("identityName", "");
					jsonMap.put("phoneNo", user.getMobile());
					jsonMap.put("utmSource", user.getUtm_source());
					jsonMap.put("depositDockUserId", user.getDeposit_dock_userid());
					jsonMap.put("regTime", sdf.format(user.getReg_time()));
				} else {

					/**
					 * 修改实名认证用户名显示方式：“*名”.
					 */
					StringBuffer showname = new StringBuffer();
					if (StringUtils.isNotBlank(userInfo.getReal_name())) {
						if (userInfo.getReal_name().length() > 1) {
							showname.append("*").append(userInfo.getReal_name().substring(1));
						} else {
							showname.append(userInfo.getReal_name());
						}
					}

					jsonMap.put("idcardValidate", "Y");
					jsonMap.put("idCard", null == userInfo.getId_card() ? "" : userInfo.getId_card());
					jsonMap.put("identityName", userInfo.getReal_name());
					jsonMap.put("phoneNo", userInfo.getPhone_no());
					jsonMap.put("utmSource", user.getUtm_source());
					jsonMap.put("depositDockUserId", user.getDeposit_dock_userid());
					jsonMap.put("regTime", sdf.format(user.getReg_time()));
					jsonMap.put("showname", showname.toString());
				}
			}

		} else {
			jsonMap.put("isBinding","N");
			jsonMap.put("bankCardValidate", "N");
			jsonMap.put("idcardValidate", "N");
			jsonMap.put("idCard", "");
			jsonMap.put("identityName", "");
			jsonMap.put("phoneNo", user.getMobile());
			jsonMap.put("utmSource", user.getUtm_source());
			jsonMap.put("depositDockUserId", user.getDeposit_dock_userid());
			jsonMap.put("regTime", sdf.format(user.getReg_time()));
		}
		// 用户是否设置过登录密码
		String settingPasswordFlag = "N";
		if (StringUtils.isNotBlank(user.getPassword())) {
			settingPasswordFlag = "Y";
		}
		jsonMap.put("settingPasswordFlag", settingPasswordFlag);
//		String result = JsonUtil.getJsonStringFromMap(jsonMap);
		//是否设置交易密码
		String passwordCash=user.getPassword_cash();
		jsonMap.put("isSetTradePWD",StringUtil.isNotEmpty(passwordCash)?"Y":"N");

		ResultDTO resultDTO = new ResultDTO(ResultCode.SUCCESS);
		resultDTO.setRecord(jsonMap);
		ResponseUtil.write(response,resultDTO.toJsonString());
	}

	/**
	 * 实名认证
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/getAuth")
	public void getAuth(HttpServletRequest request, HttpServletResponse response) throws Exception {

		String logInfo = "实名认证—getAuth ";
		logger.info(logInfo+"开始");
		//签名校验
		if (!RequestUtil.validSign(request)) {
			logger.info(logInfo+"无效签名");
			ResponseUtil.write(response, ResultConstant.INVALID_SIGN);
			return;
		}

		//token校验
		if (!RequestUtil.validToken(request)) {
			logger.info(logInfo+"无效token");
			ResponseUtil.write(response, ResultConstant.INVALID_TOKEN);
			return;
		}

		//未登录校验
		RequestHeader header = RequestUtil.decodeHeader(request);
		if (header.getUserId() == null) {
			ResponseUtil.write(response, ResultConstant.NOT_LOGIN);
			return;
		}

		//返回结果集map
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		// 解密请求参数
		Map<String, Object> paramsMap =RequestUtil.decodeData(request);
		String userId = header.getUserId().toString();// 用户id
		String idCard = (String)paramsMap.get("idCard");
		String nameCard = (String)paramsMap.get("nameCard");
		paramsMap.put("userId",userId);
		logInfo=logInfo+userId;

		if (StringUtils.isBlank(userId)) {
			logger.error(logInfo+"实名认证数据检查失败：用户id为空");
			ResultDTO resultDTO=new ResultDTO(ResultCode.FAILED,"实名认证数据检查失败：用户id为空");
			ResponseUtil.write(response,resultDTO);
			return;
		}

		if (StringUtils.isBlank(idCard)) {
			logger.error(logInfo+"实名认证数据检查失败：身份证号码为空");
			ResultDTO resultDTO=new ResultDTO(ResultCode.FAILED,"实名认证数据检查失败：身份证号码为空");
			ResponseUtil.write(response,resultDTO);
			return;
		}

		if (idCard.length() != 18 && idCard.length() != 15) {
			logger.error(logInfo+"实名认证数据检查失败：身份证号码位数校验失败");
			ResultDTO resultDTO=new ResultDTO(ResultCode.FAILED,"请输入正确的身份证号！");
			ResponseUtil.write(response,resultDTO);
			return;
		}
		idCard = idCard.toUpperCase();
		// 当前时间
		Date nowDate = userService.getSysdate();
		// 获取两个限制年龄，暂定18到80
		int minage = 18;
		int maxage = 80;
		try {
			minage = Integer.valueOf(userService.getSystemSettingValue("realname_min_age"));
			maxage = Integer.valueOf(userService.getSystemSettingValue("realname_max_age"));
			logger.info(logInfo+"查询系统参数表，实名认证限制最小年龄：" + minage + "，实名认证限制最大年龄：" + maxage);
		} catch (Exception e1) {
			logger.error(logInfo+"获取实名认证限制年龄参数异常", e1);
			ResultDTO resultDTO=new ResultDTO(ResultCode.FAILED,"获取实名认证限制年龄参数异常");
			ResponseUtil.write(response,resultDTO);
			return;
		}

		int age = IdNOToAge(idCard, nowDate);
		if (age < minage) {
			logger.error(logInfo+"未满18周岁，不符合实名认证资格");
			ResultDTO resultDTO=errorMessageService.getResultDtoByErrorMessge(errorMessageService.getErrorMessage("EM000000028"));
			ResponseUtil.write(response,resultDTO);
			return;
		}
		if (age > maxage) {
			logger.error(logInfo+"大于80周岁，不符合实名认证资格");
			ResultDTO resultDTO=errorMessageService.getResultDtoByErrorMessge(errorMessageService.getErrorMessage("EM000000029"));
			ResponseUtil.write(response,resultDTO);
			return;
		}

		// 边界年龄，精确到天
		Date bir = getBirthdayByIdNO(idCard);
		if (age == minage) {
			int cha = daysBetweenByMouthDay(bir, nowDate);
			if (cha > 0) {
				logger.error(logInfo+"未满18周岁，不符合实名认证资格");
				ResultDTO resultDTO=errorMessageService.getResultDtoByErrorMessge(errorMessageService.getErrorMessage("EM000000028"));
				ResponseUtil.write(response,resultDTO);
				return;
			}
		}
		if (age == maxage) {
			int cha = daysBetweenByMouthDay(bir, nowDate);
			if (cha < 0) {
				logger.error(logInfo+"大于80周岁，不符合实名认证资格");
				ResultDTO resultDTO=errorMessageService.getResultDtoByErrorMessge(errorMessageService.getErrorMessage("EM000000029"));
				ResponseUtil.write(response,resultDTO);
				return;
			}
		}

		if (StringUtils.isBlank(nameCard)) {
			logger.error(logInfo+"实名认证数据检查失败：真实姓名为空");
			ResultDTO resultDTO=new ResultDTO(ResultCode.FAILED,"实名认证数据检查失败：真实姓名为空");
			ResponseUtil.write(response,resultDTO);
			return;
		}

		try {
			// 查询用户信息
			User user = userService.getUserDetail(userId);
			if (null == user) {
				logger.error(logInfo+"实名认证数据检查失败：用户信息查询失败");
				ResultDTO resultDTO=new ResultDTO(ResultCode.FAILED,"实名认证数据检查失败：用户信息查询失败");
				ResponseUtil.write(response,resultDTO);
				return;
			}

			// 1.实名认证校验
			jsonMap = this.userService.idCardValidate(idCard, user.getIdcard_validate());
			if (!Consts.SUCCESS_CODE.equals(jsonMap.get("rescode"))) {
				logger.info(logInfo+"实名认证校验：" + jsonMap.get("resmsg_cn"));
				ResultDTO resultDTO=new ResultDTO(ResultCode.FAILED, (String) jsonMap.get("resmsg_cn"));
				ResponseUtil.write(response,resultDTO);
				return;
			}

			// 2.实名认证当日次数是否超限
			// 3.实名认证
			jsonMap = this.userService.getAuthNew(paramsMap, user,logInfo);

			if (!Consts.SUCCESS_CODE.equals(jsonMap.get("rescode"))) {
				logger.info(logInfo+"实名认证：" + jsonMap.get("resmsg_cn"));
				ResultDTO resultDTO=new ResultDTO(ResultCode.FAILED, (String) jsonMap.get("resmsg_cn") );
				ResponseUtil.write(response,resultDTO);
				return;
			}


			if (null != user.getId() && !StringUtil.isEmpty(user.getMobile())) {
				logger.info(logInfo+" 开始执行---->实名认证送积分 userId" + userId + "####");
				pointService.realnamePoint(user);
				logger.info(logInfo+" 执行结束---->实名认证送积分 userId" + userId + "####");
			} else {
				logger.info(
						logInfo+" 实名认证送积分时，用户信息有误，userId=" + user.getId() + ",mobile=" + user.getMobile() + " ####");
			}
			logger.info(logInfo+"结束");
			// 处理返回结果
			ResultDTO resultDTO=new ResultDTO(ResultCode.SUCCESS,Consts.SUCCESS_DESCRIBE);
			ResponseUtil.write(response,resultDTO);
		} catch (Exception e) {
			logger.error(logInfo+"实名认证息异常",e);
			logger.info(logInfo+"实名认证当日次数是否超限：" + jsonMap.get("resmsg_cn"));
			ResultDTO resultDTO=new ResultDTO(ResultCode.FAILED, "实名认证失败，请联系客服！" );
			ResponseUtil.write(response,resultDTO);
		}

	}

	// 根据身份证号得到年龄
	public int IdNOToAge(String IdNO, Date nowDate) {
		int leh = IdNO.length();
		String dates = "";
		if (leh == 18) {
			dates = IdNO.substring(6, 10);
		} else {
			dates = IdNO.substring(6, 8);
			dates = "19" + dates;
		}
		SimpleDateFormat df = new SimpleDateFormat("yyyy");
		String year = df.format(nowDate);
		int u = Integer.parseInt(year) - Integer.parseInt(dates);
		return u;

	}

	public static Date getBirthdayByIdNO(String IdNO) throws ParseException {
		int leh = IdNO.length();
		String date = "";
		if (leh == 18) {
			date = IdNO.substring(6, 14);
		} else {
			date = IdNO.substring(6, 12);
			date = "19" + date;
		}
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
		return df.parse(date);
	}

	/**
	 * 计算两个日期之间相差的天数
	 * 
	 * @param smdate
	 *            较小的时间
	 * @param bdate
	 *            较大的时间
	 * @return 相差天数
	 * @throws ParseException
	 */
	public static int daysBetween(Date smdate, Date bdate) throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		smdate = sdf.parse(sdf.format(smdate));
		bdate = sdf.parse(sdf.format(bdate));
		Calendar cal = Calendar.getInstance();
		cal.setTime(smdate);
		long time1 = cal.getTimeInMillis();
		cal.setTime(bdate);
		long time2 = cal.getTimeInMillis();
		long between_days = (time2 - time1) / (1000 * 3600 * 24);

		return Integer.parseInt(String.valueOf(between_days));
	}

	/**
	 * 计算两个日期之间相差天数，不考虑年份，只考虑月日
	 * 
	 * @param smdate
	 * @param bdate
	 * @return
	 * @throws ParseException
	 */
	public static int daysBetweenByMouthDay(Date smdate, Date bdate) throws ParseException {
		Calendar cal2 = Calendar.getInstance();
		cal2.setTime(bdate);
		int year2 = cal2.get(Calendar.YEAR);

		Calendar cal1 = Calendar.getInstance();
		cal1.setTime(smdate);
		cal1.set(Calendar.YEAR, year2);
		smdate = cal1.getTime();

		int cha = daysBetween(smdate, bdate);

		return cha;
	}

	/**
	 * 获取用户验证信息
	 * 
	 * @param request
	 * @return response
	 * @throws Exception
	 */
	@RequestMapping(value = "/getUserVerifyInfo")
	public void getUserVerifyInfo(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		String userId = paramsMap.get("userId");// 用户id

		if (StringUtils.isBlank(userId)) {
			logger.error("获取用户验证信息数据检查失败：用户id为空");
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, "",
					Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			return;
		}

		try {
			// 判断是否已实名认证
			User user = this.userService.getUserDetail(userId);
			// 实名认证
			if ("Y".equals(user.getIdcard_validate()) && "1".equals(user.getIs_create_acct())) {
				jsonMap.put("idcardVerify", "Y");
			} else {
				jsonMap.put("idcardVerify", "N");
			}
			// 设置交易密码
			if (StringUtils.isNotEmpty(user.getPassword_cash())) {
				jsonMap.put("passwordCash", "Y");
			} else {
				jsonMap.put("passwordCash", "N");
			}
			// 是否绑卡
			Map<String, Object> requestMap = new HashMap<String, Object>();
			requestMap.put("userId", userId);
			Map<String, Object> userCardMap = this.userCardService.queryUserCardInfoByUserId(requestMap);

			if (Integer.parseInt(userCardMap.get("userCardInfoCount").toString()) != 0) {
				jsonMap.put("buildIdCard", "Y");
			} else {
				jsonMap.put("buildIdCard", "N");
			}
			// 是否有头像
			UserInfo userInfo = this.userService.getUserInfo(userId);
			if (userInfo != null && StringUtils.isNotEmpty(userInfo.getImage_icon_dispose())) {
				jsonMap.put("imageIcon", "Y");
				jsonMap.put("imageIconUrl", userInfo.getImage_icon_dispose());
			} else {
				jsonMap.put("imageIcon", "N");
				jsonMap.put("imageIconUrl", "");
			}

			String result = CommonUtil.setResultStringCn(jsonMap, Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE, "");
			// 处理返回结果
			CommonUtil.responseJson(result, response);
		} catch (Exception e) {
			logger.error("获取用户验证信息异常:" + e.getMessage());
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, "",
					Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
		}
	}

	/**
	 * 删除微信绑定关系
	 * 
	 * @param request
	 * @return response
	 * @throws Exception
	 */
	@RequestMapping(value = "/deleteWeixinBingding")
	public void deleteWeixinBingding(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		String userId = paramsMap.get("userId");// 用户id

		if (StringUtils.isBlank(userId)) {
			logger.error("删除绑定关系数据检查失败：用户id为空");
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, "",
					Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			return;
		}

		try {
			// 删除微信绑定关系
			int count = this.userService.deleteWeixinBingding(userId);
			String result = CommonUtil.setResultStringCn(jsonMap, Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE, "");
			// 处理返回结果
			CommonUtil.responseJson(result, response);
		} catch (Exception e) {
			logger.error("删除绑定关系数据信息异常:" + e.getMessage());
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, "",
					Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
		}
	}

	/**
	 * 根据身份证号和手机号查询是否存在信息
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/queryUserInfoByIDCardAndMobile")
	public void queryUserInfoByIDCardAndMobile(HttpServletRequest request, HttpServletResponse response) {
		String logInfo="";
		try {
			if (!RequestUtil.validSign(request)) {
				logger.info("无效签名");
				ResponseUtil.write(response, ResultConstant.INVALID_SIGN);
				return;
			}
			if (!RequestUtil.validToken(request)) {
				logger.info("无效token");
				ResponseUtil.write(response, ResultConstant.INVALID_TOKEN);
				return;
			}
			RequestHeader header = RequestUtil.decodeHeader(request);
			logger.info("header：" + header.toString());

			Long userId = header.getUserId();
			if (userId == null) {
				ResponseUtil.write(response, ResultConstant.NOT_LOGIN);
				return;
			}
		    User user = this.userService.getUserDetail(userId.toString());
		    if(user==null){
		    	ResultDTO<String> result = new ResultDTO<>(ResultCode.FAILED,
						Message.CnDescriptionExpression.BUSINESSE_ERROR);
				ResponseUtil.write(response, result);
				return;
		    }
			
			String mobile=user.getMobile();
			// 解密请求参数
			logInfo="用户mobile="+mobile;
			JSONObject paramsMap = RequestUtil.decodeDataJson(request);
			logger.info("data：" + paramsMap.toString());

			String idCard = paramsMap.getString("idCard");
			if (StringUtils.isBlank(mobile)) {
				logger.info(logInfo+"根据身份证号和手机号查询是否存在信息检查失败：手机号为空");
				
				ResultDTO<String> checkDto = new ResultDTO<>(ResultCode.FAILED,
						Message.CnDescriptionExpression.BUSINESSE_ERROR);
				ResponseUtil.write(response, checkDto);
				return;
			}

			if (StringUtils.isBlank(idCard)) {
				logger.info(logInfo+"根据身份证号和手机号查询是否存在信息失败：身份证为空");
				ResultDTO<String> checkDto = new ResultDTO<>(ResultCode.FAILED,
						Message.CnDescriptionExpression.BUSINESSE_ERROR);
				ResponseUtil.write(response, checkDto);
				return;
			}
			paramsMap.put("mobile", mobile);

			ResultDTO<String> result = this.userService.queryUserInfoByIDCardAndMobile(paramsMap);
			ResponseUtil.write(response, result);
			return;
		} catch (Exception e) {
			logger.error(logInfo+"根据身份证号和手机号查询是否存在信息异常:" ,e);
			ResultDTO<String> result = new ResultDTO<>(ResultCode.FAILED,
					Message.CnDescriptionExpression.BUSINESSE_ERROR);
			ResponseUtil.write(response, result);
			return;
		}
	}

	/**
	 * 查询用户是否存在，查询交易密码是否正确,交易密码是否升级
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/checkUserAndPasswordCash")
	public void checkUserAndPasswordCash(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);

		String mobile = paramsMap.get("mobile");
		String passwordCash = paramsMap.get("passwordCash");
		String checkFlag = paramsMap.get("checkFlag");// 查询标识

		if (StringUtils.isBlank(checkFlag)) {
			logger.error("查询交易密码相关信息信息检查失败：查询标识为空");
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, "",
					Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			return;
		}

		if (StringUtils.isBlank(mobile)) {
			logger.error("查询交易密码相关信息信息检查失败：手机号为空");
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, "",
					Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			return;
		}
		if (StringUtils.isBlank(passwordCash)) {
			logger.error("查询交易密码相关信息信息检查失败：交易密码为空");
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, "",
					Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			return;
		}
		try {
			jsonMap = this.userService.queryPasswordCashInfo(mobile, passwordCash, checkFlag);

			String result = JsonUtil.getJsonStringFromMap(jsonMap);
			CommonUtil.responseJson(result, response);
		} catch (Exception e) {
			logger.error("查询交易密码相关信息信息异常:" + e.getMessage());
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, "",
					Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
		}

	}

	/**
	 * 密码校验
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/checkLoginPWD")
	public void checkLoginPWD(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);

		String userId = paramsMap.get("userId");
		String password = paramsMap.get("password");

		if (StringUtils.isBlank(userId)) {
			logger.error("验证登录密码数据检查失：userId为空");
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, "",
					Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			return;
		}
		if (StringUtils.isBlank(password)) {
			logger.error("验证登录密码数据检查失败：password为空");
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, "",
					Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			return;
		}
		try {
			jsonMap = this.userService.checkLoginPWD(paramsMap);
			String result = JsonUtil.getJsonStringFromMap(jsonMap);
			CommonUtil.responseJson(result, response);
		} catch (Exception e) {
			logger.error("验证登录密码异常:" + e.getMessage());
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, "",
					Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
		}
	}
}
